package com.xtgg.main;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.RequestParams;
import com.umeng.analytics.MobclickAgent;
import com.xtgg.R;
import com.xtgg.history.HistorySumActivity;
import com.xtgg.login.LoginActivity;
import com.xtgg.manager.BaseActivity;
import com.xtgg.model.Resp;
import com.xtgg.sys.Constants;
import com.xtgg.sys.DemoApp;
import com.xtgg.util.ImageLoaderHelper;
import com.xtgg.util.MgqDataHandler;
import com.xtgg.util.MgqRestClient;
import com.xtgg.util.PreferencesUtils;
import com.xtgg.util.TLog;
import com.xtgg.util.ToastUtil;
import com.xtgg.util.Utils;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;

public class DistributeActivity extends BaseActivity implements OnClickListener {

	JSONObject mInfo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_distribute);

		mInfo = JSON.parseObject(getIntent().getStringExtra("baby"));

		((TextView) findViewById(R.id.center)).setText("寻人信息");
		((Button) findViewById(R.id.right)).setText("完成");
		((Button) findViewById(R.id.right)).setTextColor(Color
				.parseColor("#EE7C1C"));

		findViewById(R.id.left).setOnClickListener(this);
		findViewById(R.id.right).setOnClickListener(this);
		 findViewById(R.id.action0).setOnClickListener(this);
		 findViewById(R.id.action1).setOnClickListener(this);
		findViewById(R.id.action2).setOnClickListener(this);
		findViewById(R.id.img0).setOnClickListener(this);
		findViewById(R.id.img1).setOnClickListener(this);
		findViewById(R.id.img2).setOnClickListener(this);

		((TextView) findViewById(R.id.value0)).setText(mInfo
				.getString("description"));
		((TextView) findViewById(R.id.value2)).setText(mInfo
				.getString("childname"));
		((TextView) findViewById(R.id.value4))
				.setText(mInfo.getString("birth"));
		
		if(mInfo.getIntValue("sex") == 0) ((TextView) findViewById(R.id.value3)).setText("男宝宝/女宝宝");	
		else ((TextView) findViewById(R.id.value3)).setText(mInfo.getIntValue("sex") == 1 ? "男宝宝" : "女宝宝");

		((TextView) findViewById(R.id.value7)).setText(PreferencesUtils
				.getString(this, "username"));
		((TextView) findViewById(R.id.value8)).setText(PreferencesUtils
				.getString(this, "telephone"));
		((TextView) findViewById(R.id.value9)).setText(PreferencesUtils
				.getString(this, "address"));
	}

	int mSelect = 0;
	Dialog mDialog = null;
	private File mPhotoFile[] = new File[3];

	void showImagePicker() {
		mDialog = new Dialog(this, R.style.Dialog_Fullscreen);
		mDialog.setContentView(R.layout.dialog_img_choose);
		mDialog.findViewById(R.id.camera).setOnClickListener(this);
		mDialog.findViewById(R.id.pic).setOnClickListener(this);
		mDialog.findViewById(R.id.cancel).setOnClickListener(this);
		mDialog.findViewById(R.id.dialog_layout).setOnClickListener(this);
		mDialog.findViewById(R.id.show).setOnClickListener(this);
		mDialog.findViewById(R.id.show).setVisibility(View.GONE);
		mDialog.show();
	}

	public void showSex() {
		final String[] items = { "男宝宝", "女宝宝", "取消" };
		new AlertDialog.Builder(this).setTitle("选择性别")
				.setItems(items, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (which < 2) {
							((TextView) findViewById(R.id.value3))
									.setText(items[which]);
						}

						dialog.dismiss();
					}
				}).show();
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.left:
			finish();
			break;

		case R.id.right:
			sendHttpRequest();
			break;

		case R.id.action0:
			showSex();
			break;

		case R.id.action1:
		{
			final Calendar c = Calendar.getInstance();
			int mYear = c.get(Calendar.YEAR);
			int mMonth = c.get(Calendar.MONTH);
			int mDay = c.get(Calendar.DAY_OF_MONTH);
			new DatePickerDialog(this, new OnDateSetListener() {
				@Override
				public void onDateSet(DatePicker arg0, int arg1, int arg2,
						int arg3) {
					StringBuffer buffer = new StringBuffer();
					buffer.append(arg1);
					buffer.append("-");
					arg2++;
					if (arg2 < 10)
						buffer.append(0);
					buffer.append(arg2);
					buffer.append("-");
					if (arg3 < 10)
						buffer.append(0);
					buffer.append(arg3);

					((TextView) findViewById(R.id.value4)).setText(buffer
							.toString());
				}
			}, mYear, mMonth, mDay).show();
			break;
		}

		case R.id.action2: {
			final Calendar c = Calendar.getInstance();
			int mYear = c.get(Calendar.YEAR);
			int mMonth = c.get(Calendar.MONTH);
			int mDay = c.get(Calendar.DAY_OF_MONTH);
			new DatePickerDialog(this, new OnDateSetListener() {
				@Override
				public void onDateSet(DatePicker arg0, int arg1, int arg2,
						int arg3) {
					StringBuffer buffer = new StringBuffer();
					buffer.append(arg1);
					buffer.append("-");
					arg2++;
					if (arg2 < 10)
						buffer.append(0);
					buffer.append(arg2);
					buffer.append("-");
					if (arg3 < 10)
						buffer.append(0);
					buffer.append(arg3);

					((TextView) findViewById(R.id.value5)).setText(buffer
							.toString());
				}
			}, mYear, mMonth, mDay).show();
			break;
		}

		case R.id.show: {
			mDialog.dismiss();
			mDialog = null;

			Intent intent = new Intent(this, SingleImageShowActivity.class);
			intent.putExtra("url", PreferencesUtils.getString(this, "headurl"));
			startActivity(intent);
		}
			break;

		case R.id.img0:
		case R.id.img1:
		case R.id.img2:
			mSelect = (arg0.getId() - R.id.img0) / 2;
			showImagePicker();
			break;

		case R.id.cancel:
		case R.id.dialog_layout:
			mDialog.dismiss();
			mDialog = null;
			break;

		case R.id.camera:
			mDialog.dismiss();
			mDialog = null;
			String state = Environment.getExternalStorageState();
			if (state.equals(Environment.MEDIA_MOUNTED)) {
				Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
				startActivityForResult(intent, 4);
			}
			break;

		case R.id.pic:
			mDialog.dismiss();
			mDialog = null;
			Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
			getAlbum.setType("image/*");
			startActivityForResult(getAlbum, 3);
			break;
		}
	}

	@SuppressWarnings({ "deprecation" })
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data == null)
			return;

		Bitmap bitmap = null;
		if (resultCode == RESULT_OK) {
			if (requestCode == 10) {
				((TextView) findViewById(R.id.value0)).setText(data
						.getStringExtra("content"));
				return;
			} else if (requestCode == 11) {
				((TextView) findViewById(R.id.value1)).setText(data
						.getStringExtra("content"));
				return;
			} else if (requestCode == 12) {
				((TextView) findViewById(R.id.value3)).setText(data
						.getStringExtra("content"));
				return;
			} else if (requestCode == 13) {
				((TextView) findViewById(R.id.value4)).setText(data
						.getStringExtra("content"));
				return;
			}

			if (requestCode == 4) {
				Uri uri = data.getData();
				if (uri != null) {
					bitmap = BitmapFactory.decodeFile(uri.getPath());
				}

				if (bitmap == null) {
					Bundle bundle = data.getExtras();
					if (bundle != null) {
						bitmap = (Bitmap) bundle.get("data");
					}
				}
			} else if (requestCode == 3) {
				Uri uri = data.getData();
				String[] proj = { MediaStore.Images.Media.DATA };
				Cursor cursor = managedQuery(uri, proj, null, null, null);
				int column_index = cursor
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				bitmap = Utils
						.getImageThumbnail(cursor.getString(column_index));
			}

			if (bitmap == null)
				return;

			if (mSelect == 0)
				mPhotoFile[mSelect] = new File(Constants.PIC_PATH);
			else if (mSelect == 1)
				mPhotoFile[mSelect] = new File(Constants.PIC_PATH_0);
			else if (mSelect == 2)
				mPhotoFile[mSelect] = new File(Constants.PIC_PATH_1);
			mPhotoFile[mSelect].deleteOnExit();

			try {
				BufferedOutputStream bos = new BufferedOutputStream(
						new FileOutputStream(mPhotoFile[mSelect]));
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
				bos.flush();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

			((ImageView) findViewById(R.id.img0 + mSelect * 2))
					.setImageBitmap(bitmap);
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	private void sendHttpRequest() {
		String place = ((EditText) findViewById(R.id.value6)).getText()
				.toString();
		String time = ((TextView) findViewById(R.id.value5)).getText()
				.toString();
		if (place.length() == 0 || time.length() == 0) {
			ToastUtil.showToastWithAlertPic("请输入失踪时间&失踪地点");
			return;
		}

		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				TLog.d(TAG, "response=" + response);
				Resp ruser = JSON.parseObject(response, Resp.class);

				if (ruser.getState().equals("1")) {
					ToastUtil.showToastWithAlertPic("寻人信息发布成功");
					finish();
				}
				else if (ruser.getState().equals("2"))
				{
					showExitDialog();
				} 
				else {
					ToastUtil.showToastWithAlertPic(ruser.getMessage());
				}
			}
		};
		// -----------------------
		
		JSONObject obj = mInfo.getJSONArray("devices").getJSONObject(0);

		RequestParams params = new RequestParams();
		params.put("act", "publishInfo");
		params.put("userid", PreferencesUtils.getString(this, "userid"));

		params.put("childname", ((EditText) findViewById(R.id.value2))
				.getText().toString());
		params.put("info_sex", mInfo.getString("sex"));
		params.put("birth", mInfo.getString("birth"));
		params.put("description", ((EditText) findViewById(R.id.value0))
				.getText().toString());
		params.put("remark", ((EditText) findViewById(R.id.value1)).getText()
				.toString());
		params.put("missplace", ((EditText) findViewById(R.id.value6))
				.getText().toString());
		params.put("misstime", ((TextView) findViewById(R.id.value5)).getText()
				.toString());
		params.put("contacts", ((EditText) findViewById(R.id.value7)).getText()
				.toString());
		params.put("contacttel", ((EditText) findViewById(R.id.value8))
				.getText().toString());
		params.put("contactaddress", ((EditText) findViewById(R.id.value9))
				.getText().toString());
		params.put("deviceid", obj.getString("deviceid"));

		try {
			int index = 0;
			if (mPhotoFile[0] != null) {
				params.put("filename" + index, mPhotoFile[0]);
				index++;
			}

			if (mPhotoFile[1] != null) {
				params.put("filename" + index, mPhotoFile[1]);
				index++;
			}

			if (mPhotoFile[2] != null) {
				params.put("filename" + index, mPhotoFile[2]);
				index++;
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		MgqRestClient.post(Constants.INFOMGT, params, loginHandler);
	}
}
